﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using Yitter.IdGenerator;

namespace RearLivestock.Beginning.Api.Application.Command.PigletsWeanings
{
    /// <summary>
    /// 仔猪断奶添加Handler
    /// </summary>
    public class AddPigletsWeaningHandler : IRequestHandler<AddPigletsWeaningCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 仔猪断奶
        /// </summary>
        private readonly IBaseRepository<PigletsWeaning> pigletsWeaningrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddPigletsWeaningHandler> _logger;
        /// <summary>
        /// 控制器
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigletsWeaningrepository"></param>
        /// <param name="logger"></param>
        public AddPigletsWeaningHandler(IMapper mapper, IBaseRepository<PigletsWeaning> pigletsWeaningrepository, ILogger<AddPigletsWeaningHandler> logger)
        {
            this.mapper = mapper;
            this.pigletsWeaningrepository = pigletsWeaningrepository;
            _logger = logger;
        }
        /// <summary>
        /// 仔猪断奶
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(AddPigletsWeaningCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var num = 1001;
                foreach (var item in request.pigletsWeanings)
                {
                    //流水号
                    item.SerialNo=YitIdHelper.NextId().ToString();
                    //单据号
                    item.DocumentNo = DateTime.Now.ToString("yyyyMMddHHmmss") + num;
                    num++;
                }
                var res = pigletsWeaningrepository.AddRange(request.pigletsWeanings);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加仔猪断奶成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加仔猪断奶异常" + ex.Message;
                _logger.LogError("添加仔猪断奶异常" + ex.Message);
            }
            return result;
        }
    }
}
